package lldp

import (
	"encoding/json"
	"net/http"

	"gitee.com/rogax/kagent/pkg/types"
)

func (l *LLDPREQUEST) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rsp := types.Response{
		Code:    200,
		Message: "success",
		Data:    nil,
	}

	data, err := l.Get()
	if err != nil {
		log.Error("Get failed", err)
		rsp.Code = 500
		rsp.Message = err.Error()
		w.WriteHeader(http.StatusInternalServerError)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(rsp)
		return
	}

	if len(data) == 0 {
		rsp.Code = 404
		rsp.Message = "not found"
		w.WriteHeader(http.StatusNotFound)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(rsp)
		return
	}

	rsp.Data = data
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(rsp)
}
